//
//  PWSCalendarViewCell.m
//  PWSCalendar
//
//  Created by Sylar on 3/14/14.
//  Copyright (c) 2014 PWS. All rights reserved.
//
///////////////////////////////////////////////////////////////////////////
#import "PWSCalendarViewCell.h"
#import "PWSCalendarViewFlowLayout.h"
#import "PWSCalendarDayCell.h"
#import "PWSCalendarView.h"
///////////////////////////////////////////////////////////////////////////
extern NSString* PWSCalendarDayCellId;
const NSString* PWSCalendarViewCellId = @"PWSCalendarViewCellId";
///////////////////////////////////////////////////////////////////////////
@interface PWSCalendarViewCell()
<UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout>
{
    NSCalendar*        m_calendar;
    
    NSDate*            m_first_date;       // if week => select date
    NSInteger          dateNum;
}
@end
///////////////////////////////////////////////////////////////////////////
@implementation PWSCalendarViewCell
@synthesize m_collection_view;
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor clearColor]];
        
        self.type = en_calendar_type_month;
        m_calendar = [NSCalendar currentCalendar];
        m_first_date = [NSDate date];
        [self SetInitialValue];
    }
    return self;
}

- (void) SetInitialValue
{
    PWSCalendarViewFlowLayout* layout = [[PWSCalendarViewFlowLayout alloc] init];
    m_collection_view = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    [self.contentView addSubview:m_collection_view];
    
    [m_collection_view setBackgroundColor:[UIColor whiteColor]];
    [m_collection_view setDelegate:self];
    [m_collection_view setDataSource:self];
    [m_collection_view setScrollEnabled:NO];
    [m_collection_view registerClass:[PWSCalendarDayCell class] forCellWithReuseIdentifier:PWSCalendarDayCellId.copy];
//    for (int i = 0; i < 42; i++) {
//        [m_collection_view registerClass:[PWSCalendarDayCell class] forCellWithReuseIdentifier:[NSString stringWithFormat:@"%d",i]];
//    }
}

//set设置类型
- (void) setType:(enCalendarViewType)type
{
    _type = type;
    [m_collection_view reloadData];
}


- (void) SetWithDate:(NSDate*)pDate ShowType:(enCalendarViewType)pCalendarType
{
    if (pCalendarType == en_calendar_type_month)
    {
        m_first_date = [self GetFirstDayOfMonth:pDate];
    }
    else if (pCalendarType == en_calendar_type_week)
    {
        m_first_date = pDate;
    }
    
    self.type = pCalendarType;
}

// reference
- (NSDate *)dateForCellAtIndexPath:(NSIndexPath *)indexPath
{
    NSDate *firstOfMonth = [self firstOfMonthForSection:indexPath.section];
    //从第 ordinalityOfFirstDay - 1 个item开始
    NSInteger ordinalityOfFirstDay = [m_calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitWeekOfMonth forDate:firstOfMonth];
    NSDateComponents *dateComponents = [NSDateComponents new];
    //
    dateComponents.day = (1 - ordinalityOfFirstDay) + indexPath.item;
    //获取firstOfMonth时间点第dateComponents的时间点
    return [m_calendar dateByAddingComponents:dateComponents toDate:firstOfMonth options:0];
}

- (NSDate *)firstOfMonthForSection:(NSInteger)section
{
    NSDateComponents *offset = [NSDateComponents new];
    offset.month = section;
    //获取当前历法下m_first_date第0个月后的时间点(返回当前月的上个月最后一天时间)
    NSDate* rt = [m_calendar dateByAddingComponents:offset toDate:m_first_date options:0];
    return rt;
   
}

//获取传入时间点的NSDateComponents表示
- (NSDate*) GetFirstDayOfMonth:(NSDate*)pDate
{
    NSDateComponents *components = [m_calendar components:NSCalendarUnitMonth | NSCalendarUnitYear fromDate:pDate];
    NSDate* rt = [m_calendar dateFromComponents:components];
    return rt;
}

// delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger rt = 0;
    if (self.type == en_calendar_type_month)
    {    
        //第一天在一星期中的位置 日 1 一 2 ...
        NSRange rangeOfWeeks = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitWeekday forDate:m_first_date];
        NSUInteger zhouji =[[NSCalendar currentCalendar] ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitWeekOfMonth forDate:m_first_date];
        //35 42
        rt = (rangeOfWeeks.length * 6);
        //改变行数
        //一个月的天数
        NSRange daysOfMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:m_first_date];
        //该月的行数
        NSInteger shenyu = daysOfMonth.length - (8 - zhouji);
        NSInteger hangshu;
        hangshu = shenyu % 7 > 0 ? shenyu/7 + 2 : shenyu/7 + 1;
        rt = hangshu * 7;
        rt = hangshu *7 > 42 ? rangeOfWeeks.length * 6 : hangshu * 7;
    }
    else if (self.type == en_calendar_type_week)
    {
        rt = 7;
    }
    dateNum = rt;
    return rt;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PWSCalendarDayCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:PWSCalendarDayCellId.copy forIndexPath:indexPath];
    cell.pswSelectDate = _selectDate;
    
    NSDate* cell_date = [self dateForCellAtIndexPath:indexPath];
    cell.dataArray = _dataArray;
    //当前item月份和日期
    NSDateComponents *cellDateComponents = [m_calendar components:NSCalendarUnitDay|NSCalendarUnitMonth fromDate:cell_date];
    //当前时间点NSDateComponents下的月份
    NSDateComponents *firstOfMonthsComponents = [m_calendar components:NSCalendarUnitMonth fromDate:m_first_date];
    if (self.type == en_calendar_type_month)
    {
        //如果月份相同才显示
        if (cellDateComponents.month == firstOfMonthsComponents.month)
        {
            [cell SetDate:cell_date];
        }
        else
        {
            
            [cell SetDate:nil];
        }
    }
    else if (self.type == en_calendar_type_week)
    {
        if (1)
        {
            [cell SetDate:cell_date];
        }
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate respondsToSelector:@selector(PWSCalendar:didSelecteDate:)])
    {
        NSDate* date = [self dateForCellAtIndexPath:indexPath];
        //[self.delegate performSelector:@selector(PWSCalendar:didSelecteDate:) withObject:nil withObject:date];
        [self.delegate PWSCalendar:nil didSelecteDate:date];
    }
}

//- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
//
//}

#pragma mark - UICollectionViewFlowLayoutDelegate

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat itemWidth = floorf(CGRectGetWidth(m_collection_view.bounds) / 7);
    
    return CGSizeMake(itemWidth, 42);
}


@end
